module.exports = class goodsService {
  static async getAllGoodsData(page) {
    const goods = require("../model/goods")();
    return await goods
      .order("gid", "DESC")
      .limit((page - 1) * 10, page * 10)
      .select();
  }

  static async getOnlyGoodsData(gid) {
    const goods = require("../model/goods")();
    return await goods.where({ gid }).select();
  }

  static async getGoodsData(page, uid) {
    const goods = require("../model/goods")();
    return await goods
      .order("gid", "DESC")
      .where({ uid })
      .limit((page - 1) * 10, page * 10)
      .select();
  }

  static async getSum(type, uid) {
    const goods = require("../model/goods")();
    if (type === "all") return await goods.count();
    else if (type === "only") return await goods.where({ uid }).count();
    else return false;
  }

  static async addGoods(data) {
    const goods = require("../model/goods")();
    return await goods.insert(data);
  }

  // 更新个人商品数据
  static async updateGoods(data) {
    const goods = require("../model/goods")();

    let gid = data.gid;

    await goods
      .where({
        gid,
      })
      .update(data);

    return true;
  }

  // 打回操作
  static async batchDeteleGoods(data) {
    const goods = require("../model/goods")();

    let gids = data.map((item) => item.gid);

    for (let i = 0; i < data.length; i++) {
      await goods
        .where({
          gid: gids[i],
        })
        .del();
    }
    return true;
  }

  static async updateGoodsNum(data = {}) {
    const goods = require("../model/goods")();
    const gids = data.map((item) => item.gid);
    const goodsnums = data.map((item) => item.goodsnum);
    for (let i = 0; i < data.length; i++) {
      if (goodsnums[i] === 0) {
        await goods
          .where({
            gid: gids[i],
          })
          .del();
      } else {
        await goods
          .where({
            gid: gids[i],
          })
          .update({
            goodsnum: goodsnums[i],
          });
      }
    }
    return true;
  }
};
